/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webbucks;


import com.webbucks.ShoppingCartBean.CartItem;
import java.io.IOException;
import java.sql.*;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Karl Viring
 */
public class IndexServlet extends HttpServlet {
    
    //    ShoppingCartBean scb = null;
    //    CustomerBean cb = null;
    
    
    
    private List<ProductBean> getProducts() throws ServletException, IOException{
        List<ProductBean> products = null;
        try {
            products = ProductBean.list();
        }
        catch (SQLException e) {
            throw new ServletException("Cannot obtain products from DB", e);
        }
        return products;
    }
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setAttribute("hasCart","false");
        
        if (request.getParameter("action") == null) {
            ShoppingCartBean scb = (ShoppingCartBean) request.getSession().getAttribute("shoppingCart");
            if (scb != null) {
                Map<String,CartItem> cart = scb.getCart();
                request.getSession().setAttribute("total_price",scb.getTotalPrice());
                request.getSession().setAttribute("cart",cart);

            }
        }
        else if (request.getParameter("action").equals("add") || request.getParameter("action").equals("addConfirm") ) {
            ShoppingCartBean scb = (ShoppingCartBean) request.getSession().getAttribute("shoppingCart");
            if (scb == null) {
                scb = new ShoppingCartBean();
            }
            scb.addProduct(request.getParameter("id"));
            Map<String,CartItem> cart = scb.getCart();
            request.getSession().setAttribute("total_price",scb.getTotalPrice());
            request.getSession().setAttribute("cart",cart);
            request.getSession().setAttribute("shoppingCart",scb);
            request.setAttribute("products", getProducts());
            if (request.getParameter("action").equals("add")){
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
            else{
                request.getRequestDispatcher("/checkout.jsp").forward(request, response);
            }
            return;
        }
       
        else if (request.getParameter("action").equals("remove") || request.getParameter("action").equals("removeConfirm") ) {
            ShoppingCartBean scb = (ShoppingCartBean) request.getSession().getAttribute("shoppingCart");
            scb.removeProduct(request.getParameter("id"));
            Map<String,CartItem> cart = scb.getCart();
            request.getSession().setAttribute("total_price",scb.getTotalPrice());
            request.getSession().setAttribute("cart",cart);
            request.getSession().setAttribute("shoppingCart",scb);
            request.setAttribute("products", getProducts());
            if (request.getParameter("action").equals("remove")){
                request.getRequestDispatcher("/index.jsp").forward(request, response);
            }
            else{
                request.getRequestDispatcher("/checkout.jsp").forward(request, response);
            }
            return;
        }
        
        else if (request.getParameter("action").equals("checkout")) {
            CustomerBean cb = (CustomerBean) request.getSession().getAttribute("customerBean");
            if (cb == null || !cb.isAuthenticated()) { // user not logged in, move to login page
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            else {
                //user is logged in, skip login.jsp
                request.getRequestDispatcher("/checkout.jsp").forward(request, response);
                return;
            }
        }
        else if (request.getParameter("action").equals("addUser")) {
            
            //validera input för användarnamn
            String usr=request.getParameter("user");
            if (usr==null || usr.length()<1) {
                request.getSession().setAttribute("validInput",false);
                request.getSession().setAttribute("incorrectInput", "Username must be atleast 1 character long.");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            
            //kolla att user inte finns i DB
            CustomerBean cb = new CustomerBean();
            if (!cb.isUnique(usr)) {
                //usr already exists in db
                request.getSession().setAttribute("validInput",false);
                request.getSession().setAttribute("incorrectInput", "Username already exists.");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
                
            }
            else { // username is unique.
                
                // check if other input is valid
                boolean valid = inputIsCorrect(request, request.getSession(),"register");
                request.getSession().setAttribute("validInput",valid);
                if (!valid) {
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                    return;
                }
                else {
                    // all input is valid, add to db and populate cb
                    cb.addCustomer(request, request.getSession());
                    cb.setCustomer(request.getParameter("user"));
                    //Login the user to the system
                    request.getSession().setAttribute("customerBean", cb);
                    request.getSession().setAttribute("validUser", true);
                    request.getSession().setAttribute("currentUser", cb.getUsername());
                    request.getRequestDispatcher("/checkout.jsp").forward(request, response);
                    return;
                    
                }
            }
        }
        else if (request.getParameter("action").equals("login")) {
            //skapa en böna
            CustomerBean cb = new CustomerBean();
            
            String usr = request.getParameter("varUser");
            String pass = request.getParameter("pw");
            
            cb.authCustomer(usr,pass);
            
            if(cb.isAuthenticated()) {
                request.getSession().setAttribute("customerBean", cb);
                request.getSession().setAttribute("validUser", true);
                request.getSession().setAttribute("currentUser", cb.getUsername());
                
                
                ShoppingCartBean scb = (ShoppingCartBean) request.getSession().getAttribute("shoppingCart");
                
                if(scb != null){
                    request.getRequestDispatcher("/checkout.jsp").forward(request, response);
                }
                else{
                    request.setAttribute("products", getProducts());
                    request.getRequestDispatcher("/index.jsp").forward(request, response);
                    return;
                }
            }
            else{
                request.getSession().setAttribute("validUser", false);
                request.getSession().setAttribute("message", "TRY AGAIN");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            
        }
        else if (request.getParameter("action").equals("logout")) {
            request.getSession().setAttribute("customerBean", null);
            request.getSession().invalidate();
            request.setAttribute("products", getProducts());
            request.getRequestDispatcher("/index.jsp").forward(request,response);
            return;
        }
        else if (request.getParameter("action").equals("toIndex")) {
            request.setAttribute("products", getProducts());
            request.getRequestDispatcher("/index.jsp").forward(request,response);
            return;
        }
        else if (request.getParameter("action").equals("confirm")) {
            ShoppingCartBean scb = (ShoppingCartBean) request.getSession().getAttribute("shoppingCart");
            CustomerBean cb = (CustomerBean) request.getSession().getAttribute("customerBean");
            System.out.println("LOADED CART!");
            if(scb != null && cb != null){
                Map<String,String> result = scb.finishOrder(cb.getUsername());
                request.getSession().setAttribute("shoppingCart", null);
                request.getSession().setAttribute("cart", null);
                request.getSession().setAttribute("total_price", 0);
                request.setAttribute("result", result);
                request.getRequestDispatcher("/orderstatus.jsp").forward(request,response);
                return;
            }
           
        }

        else if (request.getParameter("action").equals("updateProfile")) {
          
            CustomerBean cb = (CustomerBean) request.getSession().getAttribute("customerBean");
            
            String usr = cb.getUsername();
            String oldPass = request.getParameter("pw");
            cb.authCustomer(usr,oldPass);
            
            System.out.println("TEST 1: oldPass is: " + oldPass);
            
            if(cb.isAuthenticated()) {
                // uppdatera data
                // check if other input is valid
                boolean valid = inputIsCorrect(request, request.getSession(),"update");
                request.getSession().setAttribute("validInput",valid);
                
                if(!valid){
                    request.getRequestDispatcher("/updadeCustomer.jsp").forward(request, response);
                    return;
                }
                else{
                    String newPass = request.getParameter("password");
                    String verNewPass = request.getParameter("password2");
                    
                    if (newPass == null || verNewPass == null || newPass.length() <1 ){
                        cb.updateCustomer(request, request.getSession(),oldPass);
                    }
                    else{
                        cb.updateCustomer(request, request.getSession(),newPass);
                    }
                    
                    request.getRequestDispatcher("/updateCustomer.jsp").forward(request, response);
                    return;
                }   
            }
            else{
                //updatera inte
                
                request.getSession().setAttribute("validInput", false);
                request.getSession().setAttribute("incorrectInput", "Wrong password");
                request.getRequestDispatcher("/updateCustomer.jsp").forward(request, response);
            }
            
            
            
        }
        request.setAttribute("products", getProducts());
        request.getRequestDispatcher("/index.jsp").forward(request, response);
        
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        doGet(request, response);
        
    }
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    
    
    // Check if registration input is correct
    public boolean inputIsCorrect(HttpServletRequest request,
            HttpSession sess, String type) {
        
        sess.setAttribute("incorrectInput", null);
        
        String pass1=request.getParameter("password");
        String pass2=request.getParameter("password2");
        String email= request.getParameter("email");
        String fn=request.getParameter("firstName");
        String ln= request.getParameter("lastName");
        String pnum= request.getParameter("persNumber");
        String st=request.getParameter("street");
        String city=request.getParameter("city");
        String postnum=request.getParameter("zip");
        
        boolean r = false;
        
        
        if(type.equals("register") && ( pass1 == null || pass2 == null || pass1.length() <1)){
            sess.setAttribute("incorrectInput", "Password must not be empty");
            return r;
        }
        else if (!(pass1.equals(pass2))) {
            sess.setAttribute("incorrectInput", "Passwords must match.");
            return r;
        }
        
        //email check,
        if (email==null || email.length()<1) {
            sess.setAttribute("incorrectInput", "Email must be atleast 1 character long.");
            return r;
        }
        else {
            //bara ett @
            int a = email.indexOf("@");
            int b = email.lastIndexOf("@");
            if(a==0) {
                sess.setAttribute("incorrectInput", "Incorrect email address.");
                return r;
            }
            if(!(a==b)) {
                sess.setAttribute("incorrectInput", "Incorrect email address.");
                return r;
            }
            //sista . efter @
            b = email.lastIndexOf(".");
            if (!(a<b)) {
                sess.setAttribute("incorrectInput", "Incorrect email address.");
                return r;
            }
        }
        
        if (fn==null || fn.length()<1) {
            sess.setAttribute("incorrectInput", "Firstname must be atleast 1 character long.");
            return r;
        }
        
        if (ln==null || ln.length()<1) {
            sess.setAttribute("incorrectInput", "Lastname must be atleast 1 character long.");
            return r;
        }
        
        if (!(pnum.length()==10)) {
            sess.setAttribute("incorrectInput", "Personal number must be 10 digits long.");
            return r;
        }
        else {
            try {
                System.out.println("Trying to parse pnum "+pnum);
                if (Long.parseLong(pnum)<0){
                    sess.setAttribute("incorrectInput", "Personal number must not be negative.");
                    return r;
                }
            }
            catch (NumberFormatException e) {
                System.out.println("Exception "+e);
                sess.setAttribute("incorrectInput", "Personal number must be only digits.");
                return r;
            }
        }
        
        if (st==null || st.length()<1) {
            sess.setAttribute("incorrectInput", "Street name must be atleast 1 character long.");
            return r;
        }
        
        if (city==null || city.length()<1) {
            sess.setAttribute("incorrectInput", "City must be atleast 1 character long.");
            return r;
        }
        
        if (!(postnum.length()==5)) {
            sess.setAttribute("incorrectInput", "Post number must be 5 digits long.");
            return r;
        }
        else {
            try {
                if (Integer.parseInt(postnum)<0){
                    sess.setAttribute("incorrectInput", "Post number must not be negative.");
                    return r;
                }
            }
            catch (NumberFormatException e) {
                sess.setAttribute("incorrectInput", "Post number must be only digits.");
                return r;
            }
        }
        // all checks ok, return true...
        System.out.println("all checks ok, reutrn true...");
        return r= true;
    }
}
